<template>
  <div class="users">
    <van-search
      v-model="searchKeyword"
      placeholder="请输入搜索关键词"
      show-action
      @search="onSearch"
    >
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>
    
    <van-tabs v-model:active="activeTab">
      <van-tab title="全部用户">
        <van-pull-refresh 
          v-model="refreshing" 
          @refresh="onRefresh"
        >
          <van-list
            v-model:loading="loading"
            :finished="finished"
            finished-text="没有更多了"
            @load="onLoad"
          >
            <van-swipe-cell 
              v-for="user in users" 
              :key="user.id"
              :before-close="beforeClose"
            >
              <van-cell-group>
                <van-cell
                  :title="user.name"
                  :label="`注册时间: ${user.registerDate}`"
                  is-link
                  @click="viewUser(user)"
                >
                  <template #icon>
                    <van-icon name="contact" size="30px" color="#1989fa" />
                  </template>
                  
                  <template #default>
                    <van-tag :type="user.status === 'active' ? 'success' : 'warning'">
                      {{ user.status === 'active' ? '正常' : '禁用' }}
                    </van-tag>
                  </template>
                </van-cell>
              </van-cell-group>
              
              <template #right>
                <van-button square type="primary" text="编辑" @click="editUser(user)" />
                <van-button square type="danger" text="删除" @click="deleteUser(user)" />
              </template>
            </van-swipe-cell>
          </van-list>
        </van-pull-refresh>
      </van-tab>
      
      <van-tab title="VIP用户">
        <van-list
          v-model:loading="loadingVip"
          :finished="finishedVip"
          finished-text="没有更多了"
          @load="onLoadVip"
        >
          <van-cell 
            v-for="user in vipUsers" 
            :key="user.id"
            :title="user.name"
            :label="`会员等级: ${user.vipLevel} · 到期时间: ${user.vipExpiry}`"
            is-link
            @click="viewUser(user)"
          >
            <template #icon>
              <van-icon name="vip-card-o" size="30px" color="#ffd700" />
            </template>
          </van-cell>
        </van-list>
      </van-tab>
    </van-tabs>
    
    <van-empty 
      v-if="users.length === 0 && !loading" 
      description="暂无用户数据" 
    />
    
    <!-- 用户详情弹窗 -->
    <van-popup 
      v-model:show="showUserDetail" 
      position="bottom" 
      :style="{ height: '80%' }"
      round
    >
      <van-cell-group>
        <van-nav-bar
          title="用户详情"
          left-text="关闭"
          @click-left="showUserDetail = false"
        />
        
        <van-cell center title="头像">
          <template #default>
            <van-icon name="contact" size="40px" color="#1989fa" />
          </template>
        </van-cell>
        
        <van-cell title="昵称" :value="currentUser.name" />
        <van-cell title="手机号" :value="currentUser.phone" />
        <van-cell title="邮箱" :value="currentUser.email" />
        <van-cell title="注册时间" :value="currentUser.registerDate" />
        <van-cell title="最后登录" :value="currentUser.lastLogin" />
        <van-cell title="账户状态">
          <template #default>
            <van-tag :type="currentUser.status === 'active' ? 'success' : 'warning'">
              {{ currentUser.status === 'active' ? '正常' : '禁用' }}
            </van-tag>
          </template>
        </van-cell>
        
        <van-cell-group title="会员信息" v-if="currentUser.isVip">
          <van-cell title="会员等级" :value="currentUser.vipLevel" />
          <van-cell title="到期时间" :value="currentUser.vipExpiry" />
          <van-cell title="积分余额" :value="currentUser.points" />
        </van-cell-group>
        
        <van-cell-group title="操作">
          <van-cell 
            title="编辑用户" 
            is-link 
            @click="editCurrentUser" 
          />
          <van-cell 
            :title="currentUser.status === 'active' ? '禁用账户' : '启用账户'" 
            is-link 
            @click="toggleUserStatus" 
          />
          <van-cell 
            title="重置密码" 
            is-link 
            @click="resetPassword" 
          />
        </van-cell-group>
      </van-cell-group>
    </van-popup>
    
    <!-- 编辑用户表单 -->
    <van-popup 
      v-model:show="showEditForm" 
      position="bottom" 
      :style="{ height: '80%' }"
      round
    >
      <van-form @submit="onSaveUser">
        <van-nav-bar
          title="编辑用户"
          left-text="取消"
          right-text="保存"
          @click-left="showEditForm = false"
          @click-right="onSaveUser"
        />
        
        <div class="form-content">
          <van-cell-group inset>
            <van-field
              v-model="userForm.name"
              name="昵称"
              label="昵称"
              placeholder="请输入用户昵称"
              :rules="[{ required: true, message: '请输入用户昵称' }]"
            />
            
            <van-field
              v-model="userForm.phone"
              name="手机号"
              label="手机号"
              placeholder="请输入手机号"
              type="tel"
            />
            
            <van-field
              v-model="userForm.email"
              name="邮箱"
              label="邮箱"
              placeholder="请输入邮箱"
              type="email"
            />
            
            <van-field name="picker" label="用户状态" is-link readonly>
              <template #input>
                <van-radio-group v-model="userForm.status" direction="horizontal">
                  <van-radio name="active">正常</van-radio>
                  <van-radio name="inactive">禁用</van-radio>
                </van-radio-group>
              </template>
            </van-field>
            
            <van-field name="switch" label="VIP用户">
              <template #input>
                <van-switch v-model="userForm.isVip" />
              </template>
            </van-field>
            
            <van-field
              v-if="userForm.isVip"
              v-model="userForm.vipLevel"
              name="会员等级"
              label="会员等级"
              placeholder="请输入会员等级"
            />
            
            <van-field
              v-if="userForm.isVip"
              v-model="userForm.vipExpiry"
              name="到期时间"
              label="到期时间"
              placeholder="请选择到期时间"
              is-link
              readonly
              @click="showCalendar = true"
            />
          </van-cell-group>
        </div>
      </van-form>
    </van-popup>
    
    <!-- 日历组件 -->
    <van-calendar 
      v-model:show="showCalendar" 
      @confirm="onConfirmCalendar" 
    />
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { showToast, showDialog } from 'vant'

const searchKeyword = ref('')
const activeTab = ref(0)
const refreshing = ref(false)
const loading = ref(false)
const finished = ref(false)
const loadingVip = ref(false)
const finishedVip = ref(false)

const showUserDetail = ref(false)
const showEditForm = ref(false)
const showCalendar = ref(false)

const currentUser = ref({})
const editingUser = ref(null)

const users = ref([
  {
    id: 1,
    name: '张三',
    phone: '13800138000',
    email: 'zhangsan@example.com',
    registerDate: '2023-01-15',
    lastLogin: '2023-08-20 14:30',
    status: 'active',
    isVip: true,
    vipLevel: '黄金会员',
    vipExpiry: '2024-01-15',
    points: 1280
  },
  {
    id: 2,
    name: '李四',
    phone: '13900139000',
    email: 'lisi@example.com',
    registerDate: '2023-03-22',
    lastLogin: '2023-08-19 10:15',
    status: 'active',
    isVip: false
  },
  {
    id: 3,
    name: '王五',
    phone: '13700137000',
    email: 'wangwu@example.com',
    registerDate: '2023-05-10',
    lastLogin: '2023-08-18 09:45',
    status: 'inactive',
    isVip: true,
    vipLevel: '钻石会员',
    vipExpiry: '2023-12-31',
    points: 3560
  }
])

const vipUsers = ref([])

const userForm = reactive({
  name: '',
  phone: '',
  email: '',
  status: 'active',
  isVip: false,
  vipLevel: '',
  vipExpiry: ''
})

const onSearch = () => {
  showToast(`搜索: ${searchKeyword.value}`)
}

const onRefresh = () => {
  setTimeout(() => {
    refreshing.value = false
    showToast('刷新成功')
  }, 1000)
}

const onLoad = () => {
  setTimeout(() => {
    loading.value = false
    finished.value = true
  }, 1000)
}

const onLoadVip = () => {
  setTimeout(() => {
    vipUsers.value = users.value.filter(user => user.isVip)
    loadingVip.value = false
    finishedVip.value = true
  }, 1000)
}

const beforeClose = ({ position }) => {
  switch (position) {
    case 'left':
    case 'cell':
    case 'outside':
      return true;
    case 'right':
      return new Promise((resolve) => {
        showDialog({
          title: '确定删除吗？',
          message: '删除后无法恢复',
          showCancelButton: true
        }).then(() => resolve(true)).catch(() => resolve(false));
      });
  }
}

const viewUser = (user) => {
  currentUser.value = user
  showUserDetail.value = true
}

const editUser = (user) => {
  editingUser.value = user
  Object.assign(userForm, user)
  showEditForm.value = true
}

const deleteUser = (user) => {
  showDialog({
    title: '确认删除',
    message: `确定要删除用户 "${user.name}" 吗？`,
    showCancelButton: true
  }).then(() => {
    const index = users.value.findIndex(item => item.id === user.id)
    if (index !== -1) {
      users.value.splice(index, 1)
      showToast('删除成功')
    }
  }).catch(() => {
    // 取消操作
  })
}

const editCurrentUser = () => {
  showUserDetail.value = false
  editUser(currentUser.value)
}

const toggleUserStatus = () => {
  const newStatus = currentUser.value.status === 'active' ? 'inactive' : 'active'
  currentUser.value.status = newStatus
  showToast(`用户已${newStatus === 'active' ? '启用' : '禁用'}`)
}

const resetPassword = () => {
  showDialog({
    title: '重置密码',
    message: `确定要为用户 "${currentUser.value.name}" 重置密码吗？`,
    showCancelButton: true
  }).then(() => {
    showToast('密码已重置并发送至用户邮箱')
  }).catch(() => {
    // 取消操作
  })
}

const onConfirmCalendar = (date) => {
  userForm.vipExpiry = formatDate(date)
  showCalendar.value = false
}

const formatDate = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

const onSaveUser = () => {
  if (!userForm.name) {
    showToast('请输入用户昵称')
    return
  }
  
  if (editingUser.value) {
    // 编辑模式
    const index = users.value.findIndex(item => item.id === editingUser.value.id)
    if (index !== -1) {
      users.value[index] = { ...editingUser.value, ...userForm }
    }
    showToast('编辑成功')
  }
  
  showEditForm.value = false
  resetForm()
}

const resetForm = () => {
  Object.assign(userForm, {
    name: '',
    phone: '',
    email: '',
    status: 'active',
    isVip: false,
    vipLevel: '',
    vipExpiry: ''
  })
  editingUser.value = null
}
</script>

<style scoped>
.users {
  padding-bottom: 50px;
}

.form-content {
  padding-top: 46px;
}
</style>